package com.http

import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 *
 * @author Jack 2017-12-05 14:50
 */
class HttpCallback<T> {

    companion object {
        val CODE_SUCCESS = 0
    }

    // 统一的错误处理
    private fun disposalError(code: Int) {

    }

    fun start(onSuccess: ((url: String?, data: T?) -> Unit),
              onFailed: ((url: String?, code: Int?, msg: String?) -> Unit)):
            Callback<HttpResponse<T>> {

        return object: Callback<HttpResponse<T>> {
            override fun onFailure(call: Call<HttpResponse<T>>, t: Throwable?) {
                onFailed.invoke(call.request()?.url()?.toString(), -5 , "错误请求")
            }

            override fun onResponse(call: Call<HttpResponse<T>>, response: Response<HttpResponse<T>>) {
                if(response.body()?.code == CODE_SUCCESS) {
                    Log.e("success-->", response.body().toString())
                    onSuccess.invoke(call.request()?.url().toString(), response.body()?.data)
                } else {
                    onFailed.invoke(call.request()?.url()?.toString(), response.body()?.code, response.body()?.msg)
                }
            }

        }
    }
}